#include <JXQCore/JXQGlobal>
#if defined(J_OS_UNIX) || defined(J_OS_LINUX)

#include "jfiledevice_p.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

namespace JXQ
{

FILE *JFileDevicePrivate::toFILE() const
{
	return nullptr;
}

/*-----------------------------------------------------------------------------------*/

bool JFileDevice::open(OpenMode mode)
{
	J_MUTEX_LOCKER(d_ptr->m_openMutex);
	J_D(JFileDevice)

	if( d->openCheck(mode) == false )
		return false;

	int flag = 0;

	if( mode & ReadOnly ) //读
		flag |= O_RDONLY;

	if(  mode & WriteOnly ) //写
		flag |= O_WRONLY;

	if( mode & Append ) //追加
		flag |= O_APPEND;

	if( mode & Truncate ) //清空（只对块文件有效）
		flag |= O_TRUNC;

//	if( mode & Text ) ???

	if( mode & Unbuffered ) //无缓冲
	{
		// close buffer
	}

	if( (mode & DoNotCreate) == 0 ) //打开时是否创建
		flag |= O_CREAT;

	d->m_handle = ::open(d->m_name, flag);
	if( d->m_handle < 0 )
	{
		// ...
//		setErrno();

		return false;
	}

	d_ptr->m_isOpen = true;
	d_ptr->m_openMode = mode;
	return true;
}

bool JFileDevice::open(int handle, OpenMode mode)
{
	J_UNUSED(handle);
	J_UNUSED(mode);
	return false;
}

bool JFileDevice::open(const FILE *fsp, OpenMode mode)
{
	J_UNUSED(fsp);
	J_UNUSED(mode);
	return false;
}

bool JFileDevice::close()
{
	J_MUTEX_LOCKER(d_ptr->m_openMutex);
	if( not d_ptr->m_isOpen )
		return false;

	if( ::close(d_func()->m_handle) < 0 )
	{
		// ...
//		setErrno();

		return false;
	}

	d_ptr->m_isOpen = false;
	d_ptr->m_openMode = NotOpen;
	return true;
}

} //namespace JXQ

#endif //unix/linux
